package com.example.demo.controller;


import com.example.demo.model.MessageInfo;
import com.example.demo.service.MessageService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/message")
@RestController
public class MessageController {
    @Autowired
    private MessageService messageService;


    //这里返回JSON格式
    @RequestMapping(value = "/publish",produces = "application/json")
    //这里如果不加注解@RequestBody，会发生什么呢
    public String publish( @RequestBody MessageInfo messageInfo){
        //判断合法性
        if(!StringUtils.hasLength(messageInfo.getMessage())||
        !StringUtils.hasLength(messageInfo.getTo())||!StringUtils.hasLength(messageInfo.getFrom())){
            //注意在JSON格式中""的转义
            return "{\"ok\":0}";
        }
        //存储留言
        messageService.publish(messageInfo);

        return "{\"ok\":1}";
    }
    @RequestMapping("/getList")
    public List<MessageInfo> getList(){
        return messageService.queryAll();
    }

}
